<?php

namespace app\api\controller;

use app\api\model\Company;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Log;
use think\Validate;
use think\Db;
use app\api\model\User as UserModel;
use app\api\model\Levels;
use think\Config;
use app\common\library\Sms as Smslib;
use app\api\model\Skill;


/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['sfz', 'res_info', 'changehua_name', 'login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'my', 'saveNotesFile', 'modifyBase','modifyMobile','freeMobile','bmy','auth'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {

        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function ismobile()
    {

    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $email 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改花名
     */
    public function changehua_name()
    {
        $user = $this->auth->getUser();
        $hua_name = $this->request->request('hua_name');
        if (!$hua_name) {
            $this->error(__('Invalid parameters'));
        }
        $user->hua_name = $hua_name;
        $user->save();
        $this->success();
    }

    /**
     * 查询在线简历的地址返回
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function notesfile()
    {
        $res = Db::name('user')->where('id', $this->auth->id)->field('notesfile')->find();
        $this->success('success', $res);
    }

    /**
     * 添加身份证信息
     * @throws \Exception
     */
    public function sfz()
    {
        $add = $this->request->param();
        //Log::error('data:' . json_encode($add));
        $add['card_endtime'] = date("Y-m-d", $add['card_endtime']);
//        halt($add);
        if (empty($add) || !$add) {
            $this->error('参数错误');
        }
        if (!isset($add['user_id']) || $add['user_id'] <= 0) {
            $this->error('参数错误');
        }
        if (!isset($add['mobile']) || !$add['mobile'] || !\think\Validate::regex($add['mobile'], "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $uid = $add['user_id'];
        //更新的时候删除用户uid更新
        unset($add['user_id']);

        //认证通过
        $add['verification_status'] = 1;

        $save = \think\Loader::model('user')->where('id', $uid)->update($add, false);
        //Log::error('save:' . $save);
        if ($save) {
            $this->success('success', $save);
        }

    }

    /**
     *  我的
     */
    public function my()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        //$userId = 1;
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }
        $user = UserModel::findInfoByCondition(['id' => $userId]);
        if (!$user) {
            $this->error('参数错误');
        }
        $res = [
            'hua_name' => $user['hua_name'] ? $user['hua_name'] : $user['nickname'],
            'avatar' => $user['avatar'],
            'score' => $user['score'],
            'credit' => $user['credit'],
            'money' => $user['money'],
            'notesfile' => $user['notesfile'],
            'mobile' => $user['mobile'],
            'is_expert_reg' => (int)$user['is_expert_reg'],
            'is_company_reg' => (int)$user['is_company_reg']
        ];
        //获取第一个技能
        $levelName = Skill::getUserFirst($userId);
        $res['levels_name'] = $levelName;

        //获取用户的企业信息[0:没注册企业端  1:已经注册企业端]
        $company = Company::findInfoByCondition(['user_id' => $userId]);
        $requesting = $company ? (int)$company['requesting'] : 0;
        $res['boss_status'] = (int)$user['is_company_reg'];
        if ($res['boss_status'] == 0) {
            $requesting = 0;
        }
        $res['requesting'] = $requesting;

        $this->success('success', $res);
    }

    /**
     * 微信小程序上传简历
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function saveNotesFile()
    {
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //操作的用户
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }

        //原文件名
        $orgFileName = $this->request->param('name', '');
        if (!$orgFileName) {
            $this->error(__('文件名参数错误'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        if ($suffix != "pdf") {
            $this->error(__('Uploaded file format is limited'));
        }

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //只能上传pdf
        if ($fileInfo['type'] != "application/pdf") {
            //$this->error(__('Uploaded file format is limited'));
        }

        //保存文件的额外参数
        $extparam = [
            'filename' => $orgFileName
        ];

        //验证是否为图片文件
        $imagewidth = $imageheight = 0;
        if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
            $imgInfo = getimagesize($fileInfo['tmp_name']);
            if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
                $this->error(__('Uploaded file is not a valid image'));
            }
            $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
            $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
        }
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name'])
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $params = array(
                'admin_id'    => 0,
                'user_id'     => (int)$userId,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
                'extparam'    => json_encode($extparam, JSON_UNESCAPED_UNICODE)
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);

            //保存用户简历
            UserModel::saveData($userId, ['notesfile' => $uploadDir . $splInfo->getSaveName()]);

            $this->success(__('Upload successful'), [
                'url' => $uploadDir . $splInfo->getSaveName(),
                'name' => $orgFileName
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }

    /**
     * 更新用户基本信息
     */
    public function modifyBase()
    {
        //操作的用户
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error(__('参数错误'));
        }
        $posts = $this->request->post();
        if (isset($posts['user_id'])) unset($posts['user_id']);
        if (isset($posts['token'])) unset($posts['token']);
        //保存用户基本信息
        UserModel::saveData($userId, $posts);
        $this->success('success', []);
    }

    /**
     * 更新用户手机号
     */
    public function modifyMobile()
    {
        //操作的用户
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }
        $mobile = $this->request->post('mobile', '');
        $captcha = $this->request->post("captcha", '');
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        //验证手机号
        $checkRecord = UserModel::findInfoByCondition(['mobile' => $mobile]);
        if ($checkRecord && $checkRecord['id'] != $userId) { //如果有记录，并且不是当前登录用户
            $this->error(__('手机号已被占用'));
        }

        if (!$captcha) {
            $this->error(__('验证码不正确'));
        }
        //验证刚刚发送的短信验证码
        $ret = Smslib::check($mobile, $captcha, 'register');
        if (!$ret) {
            $this->error(__('验证码不正确'));
        }

        //保存用户基本信息
        UserModel::saveData($userId, ['mobile' => $mobile]);

        $this->success('success', []);
    }

    /**
     * 手机号解绑
     */
    public function freeMobile()
    {
        //操作的用户
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }
        //保存用户基本信息
        UserModel::saveData($userId, ['mobile' => '']);

        $this->success('success', []);
    }

    /**
     *  企业端我的
     */
    public function bmy()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('参数错误');
        }
        $user = UserModel::findInfoByCondition(['id' => $userId]);
        if (!$user) {
            $this->error('参数错误');
        }
        $res = [
            'hua_name' => $user['hua_name'] ? $user['hua_name'] : $user['nickname'],
            'avatar' => $user['avatar'],
            //'score' => $user['score'],
            //'credit' => $user['credit'],
            'money' => $user['money'],
            //'notesfile' => $user['notesfile'],
            'mobile' => $user['mobile'],
            'is_expert_reg' => $user['is_expert_reg'],
            'is_company_reg' => $user['is_company_reg']
        ];

        //获取用户的企业信息[0:没注册企业端  1:已经注册企业端]
        $company = Company::findInfoByCondition(['user_id' => $userId]);
        $requesting = $company ? (int)$company['requesting'] : 0;
        $res['boss_status'] = (int)$user['is_company_reg'];
        if ($res['boss_status'] == 0) {
            $requesting = 0;
        }
        $res['requesting'] = $requesting;
        $res['company_name'] = $company['company_name'];

        $this->success('success', $res);
    }

    public function auth()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }
        $user = UserModel::findInfoByCondition(['id' => $userId]);
        if (!$user) {
            $this->error(__(' 非法操作 ！'));
        }

        $res = [
            'card_zheng' => $user['card_zheng'],
            'card_fan' => $user['card_fan'],
            'username' => $user['username'],
            'card_num' => $user['card_num'],
            'card_endtime' => $user['card_endtime']
        ];
        $this->success('success', $res);
    }

}
